package com.hmyd.hmyd_android.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.Constants;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.crypto.Crypto;
import com.hmyd.hmyd_android.dto.User;
import com.hmyd.hmyd_android.dto.VerifyCode;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.RegPatterns;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.shangzhu.apptrack.AppTrack_2423;
import com.shangzhu.apptrack.SZ_AppTrack;

/**
 * 注册
 * 
 * @author wangc
 * 
 */
@ContentView(R.layout.activity_register)
public class RegisterActivity extends BasicActivity {

	private final int SEND_REGISTER_VERIFY_CODE = 0;
	private final int REGISTER = 1;
	private final int LOGIN = 2;
	private String mCodeId;

	// 标题栏
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;

	@ViewInject(R.id.ed_phone)
	private EditText mEdPhone;// 电话号码
	@ViewInject(R.id.ed_code)
	private EditText mEdCode;// 验证码
	@ViewInject(R.id.ed_passwd)
	private EditText mEdPasswd;// 密码
	@ViewInject(R.id.ed_investment_code)
	private EditText mEdInvestmentCode;// 邀请码
	@ViewInject(R.id.btn_get_code)
	private Button mBtnGetCode;// 获取验证码
	@ViewInject(R.id.register)
	private Button mBtnRegister;

	@OnClick({ R.id.btn_get_code, R.id.register, R.id.btn_login_now, R.id.register_agreement })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_get_code:// 获取验证码
			getCode();
			break;
		case R.id.register:// 立即注册
			register();
			break;
		case R.id.btn_login_now:// 立即登录
			startActivity(new Intent(getApplicationContext(), LoginActivity.class));
			finish();
			break;
		case R.id.register_agreement:// 用户协议
			getAgresment();
			break;

		default:
			break;
		}
	}

	private void getAgresment() {
		if (AppBasic.app != null && !TextUtils.isEmpty(AppBasic.app.agreementLinkUrl)) {
			Utils.jumpURL(this, AppBasic.app.agreementLinkUrl, "惠民益贷注册协议", "", false);
		}
	}

	private void register() {
		if (TextUtils.isEmpty(mEdPhone.getText().toString().trim())) {
			MyToast.showHMToast(RegisterActivity.this, false, "手机号码不能为空");
			return;
		}
		if (TextUtils.isEmpty(mEdCode.getText().toString().trim())) {
			MyToast.showHMToast(RegisterActivity.this, false, "验证码不能为空");
			return;
		}
		
		if (TextUtils.isEmpty(mEdPasswd.getText().toString().trim())) {
			MyToast.showHMToast(RegisterActivity.this, false, "密码不能为空");
			return;
		}
	
//		if (!mEdCode.getText().toString().trim().equals(mCodeId)) {
//			MyToast.showHMToast(RegisterActivity.this, false, "验证码不正确");
//			return;
//		}

		if (Utils.regPatternsPassword(this, mEdPasswd.getText().toString().trim())) {// 密码验证不通过

		} else {
			RequestParams params2 = new RequestParams();
			params2.addBodyParameter("mobile", mEdPhone.getText().toString().trim());
			params2.addBodyParameter("password", mEdPasswd.getText().toString().trim());
			params2.addBodyParameter("codeId", mCodeId);
			params2.addBodyParameter("verifyCode", mEdCode.getText().toString().trim());
			params2.addBodyParameter("referrer", mEdInvestmentCode.getText().toString().trim());

			onRequest(REGISTER, UrlConstant.REGISTER, HttpMethod.POST, params2);
		}
	}

	private void getCode() {
		if (!RegPatterns.MobilePattern.matcher(mEdPhone.getText().toString()).matches()) {// 手机验证不通过
			MyToast.showHMToast(RegisterActivity.this, false, "请输入正确的手机号码");
		} else {
			RequestParams params = new RequestParams();
			params.addBodyParameter("mobile", mEdPhone.getText().toString());

			onRequest(SEND_REGISTER_VERIFY_CODE, UrlConstant.SENDREGISTERVERIFYCODE,
					HttpMethod.POST, params);
		}
	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case SEND_REGISTER_VERIFY_CODE:
			handler.postDelayed(runnable, 0);
			java.lang.reflect.Type type = new TypeToken<VerifyCode>() {
			}.getType();
			VerifyCode verifyCode = gson.fromJson(result, type);

			mCodeId = verifyCode.codeId;
			LogUtils.d(mCodeId);

			break;
		case REGISTER:
			MyToast.showToast(this, "注册成功");
			// mPassword
			// mRegisterPhone
			PreferencesUtils.putString(this, PreferencesUtils.USER_PHONE, mEdPhone.getText()
					.toString());
			PreferencesUtils.putString(this, PreferencesUtils.USER_PASSWORD,
					Crypto.encryptAES(mEdPasswd.getText().toString(), Crypto.PRIVATEKEY));

			login();
			// 加入99统计
			AppTrack_2423.countView(Constants.RegisterPageTopic, "注册成功", "");
		case LOGIN:
			java.lang.reflect.Type type2 = new TypeToken<User>() {
			}.getType();
			User user = gson.fromJson(result, type2);

			AppBasic.isLogin = true;
			AppBasic.isCheckIned = user.isCheckIned;
			AppBasic.totalScore = user.score;
			AppBasic.certNo = user.certNo;
			AppBasic.realName = user.realName;
			AppBasic.avatar = user.avatar;
			AppBasic.username = user.username;
			AppBasic.nickname = user.nickname;
			AppBasic.urlToken = user.urlToken;
			AppBasic.securityLevel = user.securityLevel;
			AppBasic.isSetSecurityCode = user.isSetSecurityCode;
			AppBasic.tel = user.tel;
			AppBasic.email = user.email;
			AppBasic.isVerifiedEmail = user.isVerifiedEmail;
			AppBasic.isSetSecurityQuestion = user.isSetSecurityQuestion;
			AppBasic.unReadMessageCount = user.unReadMessageCount;
			AppBasic.bindQQ = user.bindQQ;
			AppBasic.isBind = user.isBind;
			AppBasic.rewardScore = user.rewardScore;
			AppBasic.nextTimeScore = user.nextTimeScore;
			AppBasic.isCanUpdateNickname = user.isCanUpdateNickname;

			Intent intent = new Intent();
			// intent.putExtra("loginSuccess", true);
			// setResult(RESULT_OK, intent);
			intent.setClass(RegisterActivity.this, MainActivity.class);
			startActivity(intent);

			finish();
			break;
		}

	}

	private void login() {
		RequestParams params = new RequestParams();
		params.addBodyParameter("username", mEdPhone.getText().toString());
		params.addBodyParameter("password", mEdPasswd.getText().toString());

		onRequest(LOGIN, UrlConstant.LOGIN, HttpMethod.POST, params);
	}

	@Override
	public void onPostFailure(int postId, String msg) {

	}

	@Override
	protected void setParams() {
		mEdPhone.addTextChangedListener(watcher);
		mEdCode.addTextChangedListener(watcher);
		mEdPasswd.addTextChangedListener(watcher);

		home_title.setOnTouchListener(touch);
		home_title_txt.setText("注册");
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	private TextWatcher watcher = new TextWatcher() {

		@Override
		public void afterTextChanged(Editable s) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// regPatterns();
		}
	};

	protected void regPatterns() {

		if (!RegPatterns.MobilePattern.matcher(mEdPhone.getText().toString()).matches()) {// 手机验证不通过
			// mBtnGetCode.setEnabled(false);
			// mBtnRegister.setEnabled(false);
			MyToast.showHMToast(RegisterActivity.this, false, "请输入正确的手机号码");
		} else {
			if (second == 60) {
				mBtnGetCode.setEnabled(true);
			}

			String etCode = mEdCode.getText().toString().trim();
			String password = mEdPasswd.getText().toString().trim();

			if (!TextUtils.isEmpty(etCode) && !TextUtils.isEmpty(password)
					&& !TextUtils.isEmpty(mEdPhone.getText().toString())) {
				mBtnRegister.setEnabled(true);
			}
		}

	}

	private int second = 60;
	Handler handler = new Handler();
	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (second >= 0) {
				mBtnGetCode.setText(second-- + "s后重新发送");
				mBtnGetCode.setEnabled(false);
				handler.postDelayed(this, 1000);
			} else {
				mBtnGetCode.setText("获取验证码");
				mBtnGetCode.setEnabled(true);

				second = 60;

				Message message = new Message();
				message.what = 1;
				handlerStop.sendMessage(message);
			}
		
		}
	};

	final Handler handlerStop = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				handler.removeCallbacks(runnable);
				break;
			}
			super.handleMessage(msg);
		}
	};

}
